import { fetchUploadFile } from "@/api/server/recommend_question";
import { Condition } from "@/components/Condition";
import { randomNumber } from "@/utils";
import { FileWordFilled } from "@ant-design/icons";
import { Progress } from "antd";
import { PropsWithChildren, useEffect, useRef, useState } from "react";

interface IFileItemProps {
  className?: string;
  item?: any;
  onUploadSuccess?: (filename: string) => void;
}
export function FileItem(props: PropsWithChildren<IFileItemProps>) {
  const { item, onUploadSuccess } = props;
  const [uploading, setUploading] = useState(false);
  const [percent, setPercent] = useState(0);
  const [uploadError, setUploadError] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");
  const timerRef = useRef(null);

  const startUpload = (file) => {
    window.clearTimeout(timerRef.current);

    timerRef.current = setTimeout(() => {
      setErrorMsg("");
      setUploading(true);
      setUploadError(false);
      setPercent(0);
      const formData = new FormData();
      formData.append("file_type", file.type);
      formData.append("file", file);
      fetchUploadFile(formData, (a, b) => {
        setPercent((a.loaded / a.total) * 100);
      })
        .then((res) => {
          setUploading(false);
          if (res.data.success) {
            setPercent(100);
            onUploadSuccess?.(item.filename);
          } else {
            setErrorMsg(res.data.message);
            setUploadError(true);
          }
        })
        .catch((err) => {
          setUploading(false);
          setUploadError(true);
          setErrorMsg(err.toString());
        });
    }, 1000);
  };

  useEffect(() => {
    if (item.status === "wait-upload" && item.fileData) {
      startUpload(item.fileData);
    }

    return () => {
      window.clearTimeout(timerRef.current);
    };
  }, []);

  return (
    <div
      className="flex flex-row bg-white w-[200px] p-[8px] ml-[16px] relative"
      title={item.text}
    >
      <div className="flex flex-col flex-1 min-w-0 cursor-pointer">
        <div className="w-full overflow-hidden whitespace-nowrap text-ellipsis">
          {item.text}
        </div>
        <div className="text-[12px] text-[#aaa]">{item.size}</div>
      </div>
      <Condition condition={uploading}>
        <div className="absolute right-[8px] top-[12px] bg-[#ffffffaa]">
          <Progress type="circle" percent={percent} size={32} />
        </div>
      </Condition>
      <FileWordFilled
        className="text-[#28508b]"
        style={{ fontSize: 32 }}
        color="#28508b"
      />
    </div>
  );
}
